import requests
from loguru import logger

from basic基础层.parser解析文件 import read_file
from config环境文件 import ENV
from const路径管理 import TOKEN_PATH


# class Base:
#     def send_request(self, data: dict):
#         logger.info(f"接口请求信息为：{data}")
#         r = requests.request(**data)
#         logger.info(f"接口响应信息为：{r}")
#         return r.json()

def request_hook(r, *args, **kwargs):
    logger.debug(f"接口响应信息为:{r.text}")


class RequestBase:
    def __init__(self):
        self._session = requests.Session()
        self._session.headers.update({'Content-Type': 'application/json',**read_file(str(TOKEN_PATH))})
        self._session.hooks['response'] = request_hook
        self._requests = self._session

    def _post(self, api_name, url: str, data):
        log_data = {
            "method": "post",
            "url": url,
            "json": data,
            "headers": self._session.headers,
        }
        logger.debug(f"-{api_name} -- 接口请求信息为:{log_data}")
        response = self._requests.post(ENV.HOST + url, json=data)
        return response.json()

    def _put(self, api_name, url: str, data):
        log_data = {
            "method": "put",
            "url": url,
            "json": data,
            "headers": self._session.headers,
        }
        logger.debug(f"-{api_name} -- 接口请求信息为:{log_data}")
        response = self._requests.put(ENV.HOST +url, json=data)
        return response.json()

    def _get(self, api_name, url: str, params=None):
        log_data = {
            "method": "GET",
            "url": url,
            "params": params,
            "headers": self._session.headers,
        }
        logger.debug(f"-{api_name} -- 接口请求信息为:{log_data}")
        response = self._requests.get(ENV.HOST +url, params=params)
        return response.json()

    def _delete(self, api_name, url: str):
        log_data = {
            "method": "delete",
            "url": url,
            "headers": self._session.headers,
        }
        logger.debug(f"-{api_name} -- 接口请求信息为:{log_data}")
        response = self._requests.delete(ENV.HOST +url)
        return response.json()
